#include "../include/muduo/proto/dispatcher.h"
#include "../include/muduo/proto/codec.h"
#include "request.pb.h"

#include "../include/muduo/base/Logging.h"
#include "../include/muduo/base/Mutex.h"
#include "../include/muduo/net/EventLoopThread.h"
#include "../include/muduo/net/TcpClient.h"

#include <iostream>
#include <string>
#include <unistd.h>

class Client
{
public:
    typedef std::shared_ptr<google::protobuf::Message> MessagePtr;
    typedef std::shared_ptr<ouyang::TranslateResponse> TranslateResponsePtr;
    typedef std::shared_ptr<ouyang::AddResponse> AddAddResponsePtr;

public:
    Client(const std::string &sip, int sport)
        : _latch(1),
          _client(_loopthread.startLoop(), muduo::net::InetAddress(sip, sport), "Protobuf_Client"),
          _dispatcher(std::bind(&Client::onUnknownMessage, this, std::placeholders::_1,
                                std::placeholders::_2, std::placeholders::_3)),
          _codec(std::bind(&ProtobufDispatcher::onProtobufMessage, &_dispatcher,
                           std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))
    {
        // 注册业务请求的回调函数
        _dispatcher.registerMessageCallback<ouyang::TranslateResponse>(std::bind(&Client::onTranslate, this,
                                                                                 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        _dispatcher.registerMessageCallback<ouyang::AddResponse>(std::bind(&Client::onAdd, this,
                                                                           std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        // 设置客服端
        _client.setConnectionCallback(std::bind(&Client::onConnection, this, std::placeholders::_1));
        _client.setMessageCallback(std::bind(&ProtobufCodec::onMessage, &_codec, std::placeholders::_1,
                                             std::placeholders::_2, std::placeholders::_3));
    }

    // 建立链接服务器的接口，需要阻塞等待链接建立成功后返回
    void connect()
    {
        // 建立链接
        _client.connect();
        _latch.wait(); // 阻塞，等待链接建立成功
    }

    void Translate(const std::string &msg)
    {
        ouyang::TranslateRequest treq;
        treq.set_msg(msg);
        // 传入子类对象
        send(&treq);
    }

    void Add(const int &num1, const int &num2)
    {
        ouyang::AddRequest areq;
        areq.set_num1(num1);
        areq.set_num2(num2);
        send(&areq);
    }

private:
    // 基类指针
    bool send(const google::protobuf::Message *message)
    {
        if (_conn->connected())
        {
            _codec.send(_conn, *message);
            return true;
        }
        return false;
    }

    void onUnknownMessage(const muduo::net::TcpConnectionPtr &conn, const MessagePtr &message, muduo::Timestamp)
    {
        LOG_INFO << "onUnknownMessage: " << message->GetTypeName();
        conn->shutdown(); // 断开连接
    }

    void onTranslate(const muduo::net::TcpConnectionPtr &conn, const TranslateResponsePtr &message, muduo::Timestamp)
    {
        std::cout << "翻译结果: " << message->msg() << std::endl;
    }

    void onAdd(const muduo::net::TcpConnectionPtr &conn, const AddAddResponsePtr &message, muduo::Timestamp)
    {
        std::cout << "计算结果: " << message->result() << std::endl;
    }

    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected())
        {
            _latch.countDown(); // 唤醒主线程中的阻塞
            _conn = conn;
        }
        else
        {
            // 连接关闭时的操作
            _conn.reset();
        }
    }

private:
    muduo::CountDownLatch _latch;            // 阻塞等待对象
    muduo::net::EventLoopThread _loopthread; // 异步的事件监控线程
    muduo::net::TcpClient _client;           // 客户端
    ProtobufDispatcher _dispatcher;          // 请求分发器对象 --> 用于分发
    ProtobufCodec _codec;                    // protobuf协议处理器
    muduo::net::TcpConnectionPtr _conn;      // 获取建立成功的链接对象，调用指定的回调函数
};

int main()
{
    Client client("127.0.0.1", 8085);
    client.connect();

    client.Translate("Hello");
    client.Translate("你好");
    client.Translate("father");

    client.Add(11, 22);

    sleep(5);
    return 0;
}